package com.news.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.news.db.info.ContentInfo;
import com.rss.data.RssItem;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDBAdapter {

	private final Context context;
	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;

	private final static byte[] _writeLock = new byte[0]; // 同步锁

	public MyDBAdapter(Context ctx) {
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, ContentInfo.DATABASE_NAME, null,
					ContentInfo.DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL(ContentInfo.SQL_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			db.execSQL("DROP TABLE IF EXISTS titles");
			onCreate(db);
		}
	}

	// ---打开数据库---

	public MyDBAdapter open() throws SQLException {
		db = DBHelper.getWritableDatabase();
		return this;
	}

	// ---关闭数据库---

	public void close() {
		DBHelper.close();
	}

	/**
	 * 插入文章列表
	 * 
	 * @param tittle_List
	 * @param columnid
	 */
	public void insertTitle(List<Map<String, Object>> tittle_List,
			String columnid) {
		synchronized (_writeLock) {
			Iterator iter = tittle_List.iterator();
			while (iter.hasNext()) {
				ContentValues cv = new ContentValues();
				Map<String, Object> map = (Map<String, Object>) iter.next();
				cv.put(ContentInfo.COLUMNID, columnid);
				cv.put(ContentInfo.TITTLE, (String) map.get(RssItem.TITLE));
				cv.put(ContentInfo.URL, (String) map.get(RssItem.LINK));
				cv.put(ContentInfo.PUBDATE, (String) map.get(RssItem.PUBDATE));
				cv.put(ContentInfo.SUMMARY, (String) map.get(RssItem.SUMMARY));
				cv.put(ContentInfo.CONTENTREAD, (String) map.get(ContentInfo.CONTENT_CONTENTREAD));
				doInsert(ContentInfo.DATABASE_TABLE, null, cv);
			}
		}
	}

	/**
	 * 将根据文章URL标记为已读
	 * 
	 * @param table
	 * @param nullColumnHack
	 * @param values
	 */
	public void setIsRead(String url) {
		ContentValues cv = new ContentValues();
		cv.put(ContentInfo.CONTENTREAD, 1);
		String[] args = { url };

		synchronized (_writeLock) {
			db.update(ContentInfo.DATABASE_TABLE, cv, ContentInfo.URL + "=?",
					args);
		}
	}

	/**
	 * 插入文章内容
	 * 
	 * @param table
	 * @param nullColumnHack
	 * @param values
	 */
	public void updateContent(String url, String content) {
		ContentValues cv = new ContentValues();
		cv.put(ContentInfo.CONTENT, content);
		String[] args = { url };

		synchronized (_writeLock) {
			db.update(ContentInfo.DATABASE_TABLE, cv, ContentInfo.URL + "=?",
					args);
		}
	}

	// 插入操作
	private void doInsert(String table, String nullColumnHack,
			ContentValues values) {
		db.insert(table, nullColumnHack, values);
	}

	// 查询操作
	public Cursor query(String table, String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String orderBy) {
		return db.query(table, columns, selection, selectionArgs, groupBy,
				having, orderBy);
	}

	/**
	 * 根据栏目ID获取文章列表
	 * 
	 * @return
	 */
	public List<Map<String, Object>> getTitleFromDB(String columnid) {
		synchronized (_writeLock) {
			Cursor cursor = db.query(ContentInfo.DATABASE_TABLE, null,
					ContentInfo.COLUMNID + " = ?", new String[] { columnid },
					null, null, "contentpubdate desc", "0,25");
			List<Map<String, Object>> tittle_List = new ArrayList<Map<String, Object>>();
			while (cursor.moveToNext()) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("columnid",
						cursor.getString(ContentInfo.CONTENT_COLUMNID));
				map.put(RssItem.TITLE,
						cursor.getString(ContentInfo.CONTENT_TITTLE));
				map.put(RssItem.LINK, cursor.getString(ContentInfo.CONTENT_URL));
				map.put(RssItem.PUBDATE,
						cursor.getString(ContentInfo.CONTENT_PUBDATE));
				map.put(RssItem.SUMMARY,
						cursor.getString(ContentInfo.CONTENT_SUMMARY));
				map.put(ContentInfo.CONTENTREAD,
						cursor.getString(ContentInfo.CONTENT_CONTENTREAD));
				map.put(ContentInfo.CONTENT,
						cursor.getString(ContentInfo.CONTENT_CONTENT));
				tittle_List.add(map);
			}
			return tittle_List;
		}
	}
	
	/**
	 * 根据url查询文章内容
	 */
	
	public String qurryContentByUrl(String url) {
		// 按文章ID 查询文章内容图片
			String[] args = { url };
			String content = null ;
			synchronized (_writeLock) {
				Cursor cursor = db.query(ContentInfo.DATABASE_TABLE,
						ContentInfo.dbColumns, "contenturl=?", args, null,
						null, null);
				if (cursor == null || cursor.getCount() == 0) {
					if (cursor != null) {
						cursor.close();
					}
					return null;
				}
				 List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
				Map<String, Object> map;
				try {
					cursor.moveToFirst();
					do {
						content = cursor.getString(cursor.getColumnIndex(ContentInfo.CONTENT)) != null ? cursor
								.getString(cursor.getColumnIndex(ContentInfo.CONTENT)) : "";
					} while (cursor.moveToNext());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (cursor != null) {
						cursor.close();
					}
				}
				return content;
			}
	}

//	/**
//	 * 
//	 */
//	public boolean queryIsRead(String contentLink) {
//		boolean isRead = false;
//		Cursor cursor = query(ContentInfo.DATABASE_TABLE, null, ContentInfo.URL
//				+ " = ?", new String[] { contentLink }, null, null, null);
//		if (cursor.moveToNext()) {
//			if (cursor.getString(ContentInfo.CONTENT_URL).equals("1")) {
//				isRead = true;
//			} else {
//				isRead = false;
//			}
//		}
//		return isRead;
//
//	}
}
